//
//  SDSimpleImageButton.m
//  SKinDiary
//
//  Created by pcyang on 16/6/26.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDSimpleImageButton.h"
#import "SDImageCacheEx.h"

@interface SDSimpleImageButton ()
@property (strong,nonatomic) NSString *url;
@end

@implementation SDSimpleImageButton

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        self.imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentFill];
        [self setContentVerticalAlignment:UIControlContentVerticalAlignmentFill ];
    }
    return self;
}
- (void)dealloc
{
    [self clearImage];
}

- (void)clearImage
{
    [self setImage:self.defaultImage forState:UIControlStateNormal];
    //    UIImageView *image = [[UIImageView alloc] initWithFrame:self.bounds];
    //    image.image = self.defaultImage;
    //    [self addSubview:image];
    [[SDImageCacheEx sharedInstance]stopGettingImage:self.url identifier:[NSString stringWithFormat:@"com.tencent.SD.simpleImageView.%lld",(long long)self]];
    self.url = nil;
}

- (void)setImageWithURL:(NSString *)url
{
    if(nil == url || [url isEqualToString:@""])
    {
        [self clearImage];
        return;
    }
    if ([self.url isEqualToString:url])
    {
        return;
    }
    else
    {
        [self clearImage];
    }
    
    self.url = url;
    
    __weak SDSimpleImageButton* weakSelf = self;
    [[SDImageCacheEx sharedInstance]getImageWithURL:self.url
                                       identifier:[NSString stringWithFormat:@"com.tencent.SD.simpleImageView.%lld",(long long)self]
                                       completion:^(UIImage *image) {
                                           
                                           if (image!= nil)
                                           {
                                               [weakSelf setImage:image forState:UIControlStateNormal];
                                           }
                                           
                                       }];
}


//- (void)setImageWithLocalImage:(NSString *)url
//{
//
//    [self setImage:self.defaultImage forState:UIControlStateNormal];
//    __weak SDSimpleImageButton* weakSelf = self;
//
//    [[SDImageCacheEx sharedInstance] getLocalImageWithURL:url identifier:[NSString stringWithFormat:@"com.tencent.SD.simpleImageView.%lld",(long long)self] completion:^(UIImage *image) {
//        if (image!= nil)
//        {
//            [weakSelf setImage:image forState:UIControlStateNormal];
//            weakSelf.url = url;
//        }
//    }];
//
//}


@end
